/*Copyright (C) 2024  深圳极向量科技有限公司 All Rights Reserved.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.*/

package neatlogic.module.change.schedule.plugin;

import neatlogic.framework.asynchronization.threadlocal.TenantContext;
import neatlogic.framework.change.constvalue.ChangeStatus;
import neatlogic.framework.change.dto.ChangeAutoStartVo;
import neatlogic.framework.change.dto.ChangeVo;
import neatlogic.framework.scheduler.core.JobBase;
import neatlogic.framework.scheduler.dto.JobObject;
import neatlogic.framework.util.TimeUtil;
import neatlogic.module.change.dao.mapper.ChangeMapper;
import neatlogic.module.change.service.ChangeService;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Component
@DisallowConcurrentExecution
public class ChangeAutoStartJob extends JobBase {

	@Autowired
	private ChangeMapper changeMapper;
	
	@Autowired
	private ChangeService changeService;
	
	@Override
	public String getGroupName() {
		return TenantContext.get().getTenantUuid() + "-CHANGE-AUTO-START";
	}

	@Override
    public Boolean isMyHealthy(JobObject jobObject) {
        Long changeId = Long.valueOf(jobObject.getJobName());
        ChangeAutoStartVo changeAutoStartVo = changeMapper.getChangeAutoStartByChangeId(changeId);
        if (changeAutoStartVo == null) {
            return false;
        } else {
            return true;
        }
    }

	@Override
	public void reloadJob(JobObject jobObject) {
		String tenantUuid = jobObject.getTenantUuid();
		TenantContext.get().switchTenant(tenantUuid);
		Long changeId = Long.valueOf(jobObject.getJobName());
		ChangeAutoStartVo changeAutoStartVo = changeMapper.getChangeAutoStartByChangeId(changeId);
		if(changeAutoStartVo != null) {
			ChangeVo changeVo = changeMapper.getChangeById(changeId);
			if(changeVo != null && ChangeStatus.PENDING.getValue().equals(changeVo.getStatus())) {
			    try {
			        if(new SimpleDateFormat(TimeUtil.YYYY_MM_DD_HH_MM).parse(changeVo.getPlanStartTime()).after(new Date())) {
						/* 如果还没到计划开始时间，则启动定时器 **/
						JobObject.Builder newJobObjectBuilder = new JobObject
								.Builder(changeId.toString(), this.getGroupName(), this.getClassName(), TenantContext.get().getTenantUuid())
								.withBeginTime(changeAutoStartVo.getTargetTime())
								.withIntervalInSeconds(60 * 60)
								.withRepeatCount(0);
						JobObject newJobObject = newJobObjectBuilder.build();
						schedulerManager.loadJob(newJobObject);
						//System.out.println("启动定时器:" + changeId + "-" + changeVo.getPlanStartTime());
					}else {
	                    /** 如果过了计划开始时间，则开始变更 **/
	                    changeService.startChangeById(changeId, null);
	                }
			    }catch(ParseException e) {
                    e.printStackTrace();
                }
			}else {
				changeMapper.deleteChangeAutoStartByChangeId(changeId);
			}
		}
	}

	@Override
	public void initJob(String tenantUuid) {
		List<ChangeAutoStartVo> changeAutoStartList = changeMapper.getAllChangeAutoStart();
		for(ChangeAutoStartVo changeAutoStartVo : changeAutoStartList) {
			JobObject.Builder jobObjectBuilder = new JobObject
					.Builder(changeAutoStartVo.getChangeId().toString(), this.getGroupName(), this.getClassName(), TenantContext.get().getTenantUuid());
			JobObject jobObject = jobObjectBuilder.build();
			this.reloadJob(jobObject);
		}
	}

	@Override
	public void executeInternal(JobExecutionContext context, JobObject jobObject) throws JobExecutionException {
		Long changeId = Long.valueOf(jobObject.getJobName());
		ChangeAutoStartVo changeAutoStartVo = changeMapper.getChangeAutoStartByChangeId(changeId);
		if(changeAutoStartVo != null) {
			ChangeVo changeVo = changeMapper.getChangeById(changeId);
			if(changeVo != null && Objects.equals(changeVo.getAutoStart(), 1)) {
				if(ChangeStatus.PENDING.getValue().equals(changeVo.getStatus())) {
					changeService.startChangeById(changeId, null);
				}
			}
		}
		schedulerManager.unloadJob(jobObject);
		changeMapper.deleteChangeAutoStartByChangeId(changeId);
		//System.out.println("执行启动定时器:" + changeId + "-" + new Date());
	}

}
